package com.qf.hytrix.service;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.springframework.web.client.RestTemplate;

/**
 * @Auther: Song
 * @Date: 2022-03-18 18:34
 */
public class HelloCommand extends HystrixCommand<String> {
    RestTemplate restTemplate;

    public HelloCommand(RestTemplate restTemplate) {
        //开启一个名为zhangsan的子线程
        super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("zhangsan")));
        this.restTemplate = restTemplate;
    }

    /**
     *  发起请求的地方
     * @return
     * @throws Exception
     */
    @Override
    protected String run() throws Exception {
        int i = 1 / 0;
        return restTemplate.getForObject("http://storage/deduct",String.class);
    }

    /**
     * 降级服务的地方
     * @return
     */
    @Override
    protected String getFallback() {
        //获取执行时的异常（即 run 方法抛出的异常）
        Throwable throwable = getExecutionException();
        return "error---fallback--->" + throwable;
    }
}
